﻿

var mStockDetail = {} //单据明细

var mBillType;

var mEviBillEstimate;

var mSEQs = [];//caccc

$(function () {
    extendEasyUI();

    var args = getUrlArgs();

    var index = args["index"];

    mBillType = args["mBillType"];

    mEviBillEstimate = args["mEviBillEstimate"];
    mStockDetail = window.parent.mStockDetails[index];

    setBillInfoFeature();

    //默认隐藏车辆Tab
    $("#tabInfo").tabs('getTab', '车辆信息').panel('options').tab.hide();

    $("#cmbEvidenceType").combobox({
        valueField: 'Id',
        textField: 'Name',
        editable: false,
        panelHeight: 120,
        disabled: true
        //onSelect: onSelectEvidenceType
    });

    $('#txtQty').bind('blur', function () {
        $('#txtAmount').numberbox('setValue', $('#txtQty').numberbox("getValue") * mStockDetail.Evidence.Price)
    });

    $("#cmbUM").combobox({
        valueField: 'Id',
        textField: 'Name',
        editable: false,
        panelHeight: 120,
        disabled: true
        //onSelect: function (record) { mEvidence.UM = record; }
    });

    $("#cmbOrigin").combobox({
        valueField: 'Id',
        textField: 'Name',
        editable: false,
        panelHeight: 70,
        disabled: true
        //onSelect: function (record) { mEvidence.Origin = record; }
    });

    $("#cmbStorage").combotree({
        valueField: 'Id',
        textField: 'FullName',
        editable: false,

        onSelect: onSelectStorage
    });
    $('#txtCallDuration').numberbox({
        onChange: function (newValue, oldValue) {
            $('#txtDurationTime').val(getDurationTime(window.parent.mStockBill.CheckTime, newValue));
        }
    });
    loadBaseData();
    loadStoratgeModels(window.parent.mStockBillType, mStockDetail.Evidence.Id);
    dispaly();

});

//只有调用出库时候才能看见调用期限，调用到期时间
function setBillInfoFeature() {
    $('#txtSeizureDay').attr("disabled", true);
    $('#txtEstimateTime').attr("disabled", true);
    if (mBillType == 5) {
        $('#lblCallDuration').show();
        $('#txtCallDuration').show();
        $('#lblDurationTime').show();
        $('#txtDurationTime').show();
        $('#txtDurationTime').attr("disabled", true);
    } else {
        $('#lblCallDuration').hide();
        $('#txtCallDuration').hide();
        $('#lblDurationTime').hide();
        $('#txtDurationTime').hide();
    }
};

//显示
function dispaly() {

    lockStockDetailElements(window.parent.mStockBill.IsCheck);

    if (mStockDetail.Storage)
        $('#cmbStorage').combotree("setValue", mStockDetail.Storage.Id);

    if (mStockDetail.Evidence.EvidenceType)
        $('#cmbEvidenceType').combobox("select", mStockDetail.Evidence.EvidenceType.Id);

    $('#txtName').val(mStockDetail.Evidence.Name);
    $('#txtModel').val(mStockDetail.Evidence.Model);
    $('#txtFeature').val(mStockDetail.Evidence.Feature);
    
    $('#txtOriginalQty').numberbox('setValue', mStockDetail.Evidence.Qty);
    $('#txtStockQty').numberbox('setValue', mStockDetail.Evidence.StockQty);
    $('#txtOutStockQty').numberbox('setValue', mStockDetail.Evidence.OutStockQty);
    $('#txtInquiryOutStockQty').numberbox('setValue', mStockDetail.Evidence.InquiryOutStockQty);
    $('#txtQty').numberbox('setValue', mStockDetail.Qty);
    if (mBillType == 5) {
        $('#txtCallDuration').numberbox('setValue', mStockDetail.CallDuration);
        $('#txtDurationTime').val(getDurationTime(window.parent.mStockBill.CheckTime, mStockDetail.CallDuration));
    }
    if (mStockDetail.Evidence.UM)
        $('#cmbUM').combobox("select", mStockDetail.Evidence.UM.Id);

    $('#txtPrice').numberbox('setValue', mStockDetail.Evidence.Price);
    $('#txtAmount').numberbox('setValue', mStockDetail.Amount);
    $('#txtOwnerName').val(mStockDetail.Evidence.OwnerName);
    $('#txtOwnerContact').val(mStockDetail.Evidence.OwnerContact);
    $('#txtOwnerAddress').val(mStockDetail.Evidence.OwnerAddress);
    $('#txtSeizureDay').numberbox('setValue', mStockDetail.Evidence.SeizureDay);
    $('#txtEstimateTime').val(getEstimateTime(mEviBillEstimate, mStockDetail.Evidence.SeizureDay));
    if (mStockDetail.Evidence.Origin)
        $('#cmbOrigin').combobox("select", mStockDetail.Evidence.Origin.Id);
    if (mStockDetail.Storage) {
        $('#cmbStorage').combotree('setValue', mStockDetail.Storage.Id);
        $('#txtStorageFullName').val(mStockDetail.Storage.FullName);
    }

    $('#txtSerialNo').val(mEvidence.SerialNo);

    //车辆信息
    $('#txtVehicleNo').val(mStockDetail.Evidence.VehicleNo);
    $('#txtVehicleFactory').val(mStockDetail.Evidence.VehicleFactory);
    $('#txtVehicleNameplate').val(mStockDetail.Evidence.VehicleNameplate);
    $('#txtVehicleColor').val(mStockDetail.Evidence.VehicleColor);
    $('#txtVehicleUsage').val(mStockDetail.Evidence.VehicleUsage);
    $('#txtVehicleIdCode').val(mStockDetail.Evidence.VehicleIdCode);
    $('#txtVehicleEngineIdCode').val(mStockDetail.Evidence.VehicleEngineIdCode);
    $('#txtVehicleLicenceAuthority').val(mStockDetail.Evidence.VehicleLicenceAuthority);
}

function lockStockDetailElements(lock) {
    if (lock) {
        $('#btnConfirm').hide();

        $('#cmbStorage').combotree("disable");
        $('#cmbEvidenceType').combobox("disable");
        $('#txtName').attr("disabled", true);
        $('#txtModel').attr("disabled", true);
        $('#txtFeature').attr("disabled", true);
        $('#cmbUM').combobox("disable");
        $('#txtQty').attr("disabled", true);

        $('#txtPrice').attr("disabled", true);
        $('#txtOwnerName').attr("disabled", true);
        $('#txtOwnerContact').attr("disabled", true);
        $('#txtOwnerAddress').attr("disabled", true);
        $('#txtSeizureDay').attr("disabled", true);
        $('#txtEstimateTime').attr("disabled", true);
        $('#cmbOrigin').combobox("disable");
        $('#txtVehicleNo').attr("disabled", true);
        $('#txtVehicleFactory').attr("disabled", true);
        $('#txtVehicleNameplate').attr("disabled", true);
        $('#txtVehicleColor').attr("disabled", true);
        $('#txtVehicleUsage').attr("disabled", true);
        $('#txtVehicleIdCode').attr("disabled", true);
        $('#txtVehicleEngineIdCode').attr("disabled", true);
        $('#txtVehicleLicenceAuthority').attr("disabled", true);
    }
}
//读取基础资料
function loadBaseData() {
    try {
        var origins = gLoadOrigins();
        $('#cmbOrigin').combobox("loadData", origins);

        var evidenceTypes = gLoadEvidenceTypes();
        $('#cmbEvidenceType').combobox("loadData", evidenceTypes);

        var ums = gLoadUMs();
        $('#cmbUM').combobox("loadData", ums);
    } catch (ex) {
        alert(ex);
    }
}
//确保明细
function confirmAction() {
    try {
        //viewToObj();
        mStockDetail.Qty = $('#txtQty').numberbox('getValue');
        mStockDetail.Amount = $('#txtAmount').numberbox('getValue');
        if (mBillType == 5) {
            mStockDetail.CallDuration = $('#txtCallDuration').numberbox('getValue');
        }
        if (checkDetail()) {
            window.parent.loadDetails();
            window.parent.mStockDetailDlg.close();
        }

    } catch (ex) {
        alert(ex);
    }

}

function checkDetail() {
    if (!mStockDetail.Storage) {
        $.messager.alert('提示', "请选择仓位!");
        return false;
    } else {
        if (!mStockDetail.Storage.IsLeaf) {
            $.messager.alert('提示', "请选择仓位的最末级节点!");
            return false;
        }
    }

    if (mStockDetail.Qty == 0) {
        $.messager.alert('提示', "数量不能为零");
        return false;
    }
    if (mStockDetail.CallDuration == 0) {
        $.messager.alert('提示', "调用期限不能为零");
        return false;
    }
    if (mBillType == 5) {
        if (mStockDetail.CallDuration > mStockDetail.Evidence.SeizureDay) {
            $.messager.alert('提示', "调用期限不能超过预计扣押天数");
            return false;
        }
    }
    var billType = window.parent.mStockBillType;

    if (mStockDetail.Qty < mStockDetail.minQty || mStockDetail.Qty > mStockDetail.maxQty) {
        $.messager.alert('提示', "请输入正确的数量!");
        return false;
    }

    return true;
}

function getDurationTime(sTime, days) {
    var d = parseInt(days);
    var s = "";
    if (d > 0) {
        if (sTime == undefined) {
            var nows = new Date();
            sTime = nows.setDate(nows.getDate() + d);
            var newTime = new Date(sTime);
            s = newTime.getFullYear() + "-" + (newTime.getMonth() + 1) + "-" + (newTime.getDate());
        } else {
            var t = eval('new ' + sTime.substring(1, sTime.length - 1));
            var nt = t.setDate(t.getDate() + d);
            var newTime = new Date(nt);
            s = newTime.getFullYear() + "-" + (newTime.getMonth() + 1) + "-" + (newTime.getDate());
        }
        return s;
    } else {
        return "";
    }
};

function getEstimateTime(cTime, days) {
    var cETime = new Date(parseInt(cTime));
    var nt = cETime.setDate(cETime.getDate() + days);
    var newTime = new Date(nt);
    s = newTime.getFullYear() + "-" + (newTime.getMonth() + 1) + "-" + (newTime.getDate());
    return s;
};

function loadStoratgeModels(billType, evidenceId) {

    if (window.parent.mStockBill.IsCheck) { //已经审核
        buildStorageModels(mStockDetail.Storage);
    } else { //未审核

        if (billType == 2 || billType == 3) {
            loadInSEQs(evidenceId);
        } else if (billType == 4 || billType == 5) {
            loadOutSEQs(evidenceId);
        }
    }
}

//读取入库仓位信息
function loadInSEQs(evidenceId) {
    $.ajax({
        url: "/BaseData/LoadInSEQModels",
        type: "POST",
        dataType: "json",
        data: { 'evidenceId': evidenceId },
        async: false,
        success: function (req) {
            if (req.IsSuccess) {//成功填充数据
                try {
                    mSEQs = JSON.parse(req.Data);
                    var ss = seqsInConvert(mSEQs);
                }
                catch (ex) {
                    $.messager.alert('错误', ex);
                }
                $('#cmbStorage').combotree('loadData', ss);
            }
            else {
                $.messager.alert('错误', "获取仓位数据时发生错误");
            }
        }
    });
}

//读取出库仓位信息
function loadOutSEQs(evidenceId) {
    $.ajax({
        url: "/BaseData/LoadOutSEQs",
        type: "POST",
        dataType: "json",
        data: { 'evidenceId': evidenceId },
        success: function (req) {
            if (req.IsSuccess) {//成功填充数据
                try {
                    mStorageModels = JSON.parse(req.Data);
                    var ss = seqsOutConvert(mStorageModels);
                }
                catch (ex) {
                    $.messager.alert('错误', ex);
                }
                $('#cmbStorage').combotree('loadData', ss);

                if (ss.length == 1) {
                    $('#cmbStorage').combotree('setValue', ss[0].id);
                    loadStorage(ss[0].id);
                }

            }
            else {
                $.messager.alert('错误', "获取仓位数据时发生错误");
            }
        }
    });
}



//
function onSelectStorage(record) {

    loadStorage(record.id);
}

function loadStorage(id) {
    $.ajax({
        url: "/BaseData/LoadStorage",
        type: "POST",
        dataType: "json",
        data: { 'storageId': id },
        async: false,
        success: function (req) {
            if (req.IsSuccess) {//成功填充数据
                try {
                    var storage = JSON.parse(req.Data);
                    mStockDetail.Storage = storage;
                    $('#txtStorageFullName').val(mStockDetail.Storage.FullName);
                }
                catch (ex) {
                    mStockDetail.Storage = null;
                    $('#txtStorageFullName').val('');
                    $.messager.alert('错误', ex);
                }
            }
            else {
                mStockDetail.Storage = null;
                $('#txtStorageFullName').val('');
                $.messager.alert("错误", "获取数据失败");
            }
        }
    });
}

//将后台列表转化成tree格式
function seqsInConvert(seqs) {
    var ss = [];
    var count = seqs.length;

    for (var i = 0; i < count; i++) {
        var seq = seqs[i];

        seq.id = seq.StorageId;
        seq.text = seq.Name;

        if (seq.IsRecommend && seq.NodeLevel > 1) {
            var topSeq = {};
            topSeq.id = seq.id;
            topSeq.text = seq.FullName + "  ( " + seq.Description + " )";
            ss.splice(0, 0, topSeq);

            seq.text = seq.Name + "  ( " + seq.Description + " )";

        } else if (seq.Qty > 0) {
            seq.text = seq.FullName + "  ( " + seq.Description + " )";
        }

        if (!seq.IsLeaf) {
            seq.children = [];

            for (var j = 0; j < count; j++) {
                var tmp = seqs[j];
                if (tmp.ParentId == seq.StorageId) {
                    //tmp.id = tmp.StorageId;
                    //tmp.text = tmp.Name;

                    //if (tmp.IsRecommend) {
                    //    var topSeq = {};
                    //    topSeq.id = tmp.id;
                    //    topSeq.text = tmp.FullName + "  ( " + tmp.Description + " )";
                    //    ss.splice(0, 0, topSeq);

                    //    tmp.text = tmp.Name + "  ( " + tmp.Description + " )";

                    //}else if (tmp.Qty > 0) {
                    //    tmp.text = tmp.FullName + "  ( " + tmp.Description + " )";
                    //}

                    seq.children.push(tmp);
                }
            }

        }

        if (seq.NodeLevel == 1) {
            if (!seq.IsLeaf) {
                seq.state = 'closed';
            }
            ss.push(seq);
        }
    }

    return ss;
}

function seqsOutConvert(seqs) {
    var ss = [];
    var count = seqs.length;

    for (var i = 0; i < count; i++) {
        var seq = seqs[i];
        var s = {};

        s.id = seq.StorageId;
        s.text = seq.FullName;
        ss.push(s);
    }
    return ss;
}

function buildStorageModels(storage) {
    var ss = [];

    var s = {};
    s.id = storage.Id;
    s.text = storage.FullName;
    ss.push(s);

    $('#cmbStorage').combotree('loadData', ss);
}

//关闭窗口
function exitAction() {
    window.parent.mStockDetailDlg.close();
}